<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'cardd:order:carddYcdd:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    :okText="t('保存')"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #carddYcddBtList>
        <a-button
          class="mt-2 mb-2"
          @click="handleCarddYcddBtAdd"
          v-auth="'cardd:order:carddYcdd:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" />
          {{ t('新增') }}
        </a-button>
        <BasicTable @register="registerCarddYcddBtTable" @row-click="handleCarddYcddBtRowClick" @edit-change="rowChange">
          
          <template #wdlxSelect="{ record: childRecord, index }">
            <Select
              v-if="childRecord.editValueRefs.btZlfs == '1'"
              placeholder="请选择"
              v-model:value="childRecord.btWdlx"
              size="small"
              dictType="car_wdlx"
              @change="wdlxchange($event,childRecord)"
            />
            <Select
              v-if="childRecord.editValueRefs.btZlfs == '2'"
              placeholder="请选择"
              v-model:value="childRecord.btWdlx"
              size="small"
              dictType="car_wdlx_dj"
            />
            <Select
              v-if="childRecord.editValueRefs.btZlfs == '3'"
              placeholder="请选择"
              v-model:value="childRecord.btWdlx"
              size="small"
              dictType="car_wdlx_lz"
            />
          </template>
          
          
          <template #jsySelect="{ record: childRecord, index }">


            <!-- 驾驶员 -->
            <ListSelect
              placeholder="请选择"
              v-if="(childRecord.editValueRefs.btZlfs == '1'&& (childRecord.editValueRefs.btWdlx == '1' || childRecord.editValueRefs.btWdlx == '3'))
              || (childRecord.editValueRefs.btZlfs == '2'&& childRecord.editValueRefs.btWdlx == '1')
              " 
              v-model:value="childRecord.bt_jsybm"
              :labelValue="childRecord?.btJsy"
              ref="jsychlist"
              selectType="empUserSelect"
              @select="handSelectjsy($event, childRecord)"
            />

            <a-input placeholder="请输入"
             v-else-if="(childRecord.editValueRefs.btZlfs == '2' && childRecord.editValueRefs.btWdlx != '1') 
             || (childRecord.editValueRefs.btZlfs == '1' && (childRecord.editValueRefs.btWdlx == '2' || childRecord.editValueRefs.btWdlx == '4'))"  
             v-model:value="childRecord.btJsy" />

            <div  v-else>{{childRecord.btJsy}}</div>
          </template>

          <!-- 品牌型号 -->
          <template #ppxhSelect="{ record: childRecord, index }">
           <Select
              v-if="(childRecord.editValueRefs.btZlfs == '1'&& (childRecord.editValueRefs.btWdlx == '1' || childRecord.editValueRefs.btWdlx == '2'))
              || (childRecord.editValueRefs.btZlfs == '3'&& childRecord.editValueRefs.btWdlx == '1')
              " 
              placeholder="请选择"
              v-model:value="childRecord.btPpxh"
              size="small"
              dictType="car_type"
            />

            <a-input placeholder="请输入" 
            v-else-if="(childRecord.editValueRefs.btZlfs == '3' && childRecord.editValueRefs.btWdlx != '1') 
            || (childRecord.editValueRefs.btZlfs == '1' && (childRecord.editValueRefs.btWdlx == '3' || childRecord.editValueRefs.btWdlx == '4'))" 
            v-model:value="childRecord.btPpxh" />

            <div  v-else>{{childRecord.btPpxh}}</div>
          
          </template>

          <!-- 车牌号 -->
          <template #cphSelect="{ record: childRecord, index }">
            <ListSelect
              placeholder="请选择"
              v-if="(childRecord.editValueRefs.btZlfs == '1'&& (childRecord.editValueRefs.btWdlx == '1' || childRecord.editValueRefs.btWdlx == '2'))
              || (childRecord.editValueRefs.btZlfs == '3'&& childRecord.editValueRefs.btWdlx == '1')
              " 
              v-model:value="childRecord.btCph"
              :labelValue="childRecord?.btCph"
              :queryParams="{
                cllx: childRecord.btPpxh,
              }"
              ref="jsychlist"
              selectType="basCarSelect"
              @select="handSelectcph($event, childRecord)"
            />
            <a-input placeholder="请输入" 
            v-else-if="(childRecord.editValueRefs.btZlfs == '3' && childRecord.editValueRefs.btWdlx != '1') 
            || (childRecord.editValueRefs.btZlfs == '1' && (childRecord.editValueRefs.btWdlx == '3' || childRecord.editValueRefs.btWdlx == '4'))" 
            v-model:value="childRecord.btCph" />

            <div  v-else>{{childRecord.btCph}}</div>
          </template>


        </BasicTable>
      </template>
    </BasicForm>

    <template #centerFooter>
      <a-button
        class="mt-2"
        type="success"
        @click="handleSubmit('1')"
        v-auth="'cardd:order:carddYcdd:edit'"
      >
        <Icon icon="ant-design:check-outlined" />
        {{ t('发布') }}
      </a-button>
    </template>
  </BasicDrawer>
  <ListSelect
    ref="carSelectRef"
    selectType="basCarSelect"
    :queryParams="queryParams"
    @select="handleSelect"
    v-show="false"
  />
</template>
<script lang="ts" setup name="ViewsCarddOrderCarddYcddForm">
  import { ref, unref, computed, nextTick } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import dayjs from 'dayjs';
  import { CarddYcdd, carddYcddSave, carddYcddForm } from '/@/api/cardd/order/carddYcdd';
  import { coreKhlxrListData } from '/@/api/bas/cus/coreKhlxr';
  import { coreKhjgbGetKhjgb } from '/@/api/bas/cus/coreKhjgb';

  import { coreYwlxTreeData } from '/@/api/bas/ywlx/coreYwlx';
  import { CarSattleType } from '/@/enums/GlobEnum';
  import { ListSelect } from '/@/components/ListSelect';
  import { Select } from '/@/components/Form';

  
  import { coreKhlxrTreeData } from '/@/api/bas/cus/coreKhlxr';

  const emit = defineEmits(['success', 'register']);
  const carSelectRef = ref<any>(null);
  const queryParams = ref<any>(null);
  const ppxh = ref<string>();
  const dwbm = ref<string>('');
  const rowKey = ref<string>('');
  const isShow = ref<boolean>(false);

  const { t } = useI18n('cardd.order.carddYcdd');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CarddYcdd>({} as CarddYcdd);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增用车订单') : t('编辑用车订单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单编号'),
      field: 'ycddDdbh',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('用车单位'),
      field: 'ycddYcdw',
      fieldLabel: 'basCus.khdaDwqc',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'basCusSelect',
          onSelect: async (values) => {
            dwbm.value = values[0].khdaDwbm;

            // 价格
            let obj = getFieldsValue()
            let resq = await coreKhjgbGetKhjgb({
                khjgbYcdw : obj.ycddYcdw,
                khjgbCllx :'',
                khjgbZlfs :'' ,
                khjgbYwlx :obj.coreYwlx.id
             })
            let arr =  carddYcddBtTable.getDataSource()

            console.log(arr,'arr=====');

            let newArr = arr.map(item=>{
              let o = {...item}
              resq.data.forEach(item2=>{
                if(item2.khjgbCllx ==item.btPpxh && item2.khjgbZlfs ==item.btZlfs){
                  o.btJcj = item2.khjgbJcj
                  o.btJcgl = item2.khjgbJcgl
                  o.btJcsz = item2.khjgbJcsz
                  o.btCgldj = item2.khjgbCgldj
                  o.btCsdj = item2.khjgbCsdj
                }
              })
              return o
            })

            carddYcddBtTable.setTableData(newArr || []);

            console.log(newArr,'newArr=====');
            

            // 业务员
            formModel['ycddYwy'] = values[0].person ? values[0].person.userName : '';
            formModel['ycddJsfs'] = values[0].khdaJsfs;
            if (values[0].khdaJsfs === CarSattleType.PROJ) {
              // 专项结算
              updateSchema([
                {
                  field: 'ycddZxmc',
                  required: true,
                },
              ]);
            } else {
              updateSchema([
                {
                  field: 'ycddZxmc',
                  required: false,
                },
              ]);
            }
            // formModel['ycddYwy'] = values[0].person.userName;
            // 联系人 联系电话 (有默认联系人取默认联系人，多个默认取第一个，无默认联系人不取)
            const res = await coreKhlxrListData({ parentId: values[0].khdaDwbm });
            let khlxrLxrbm = '';
            let khlxrLxrmc = '';
            let dept = '';
            let phone = '';
            let defaultFlag = false
            // 遍历一次列表，找到第一个默认联系人
            for (let i = 0; i < res.list.length; i++) {
              if (res.list[i].khlxrMrlxr === '1') {
                defaultFlag = true
                // khlxrLxrbm = res.list[i].id;
                // khlxrLxrmc = res.list[i].khlxrLxrmc;
                khlxrLxrbm = res.list[i].khlxrLxrmc;
                dept = res.list[i].khlxrBm;
                phone = res.list[i].khlxrLxdh;
                break;
              }
            }
            if(!defaultFlag && res.list.length){
                  khlxrLxrbm = res.list[0].khlxrLxrmc;
                  dept = res.list[0].khlxrBm;
                  phone = res.list[0].khlxrLxdh;
            }
            // 如果找到了默认联系人，则设置表单模型中的联系人字段
            console.log('formModel', formModel);
            if (khlxrLxrbm) {
              formModel['ycddLxr'] = khlxrLxrbm;
              // formModel['ycddLxr'] = khlxrLxrbm;
              // formModel['contact.khlxrLxrmc'] = {
              //   khlxrLxrmc: khlxrLxrmc,
              // };
              formModel['ycddBm'] = dept;
              formModel['ycddLxdh'] = phone;
            } else {
              formModel['ycddLxr'] = '';
              // formModel['contact.khlxrLxrmc'] = '';
              // formModel['contact.khlxrLxrmc'] = {
              //   khlxrLxrmc: '',
              // };
              formModel['ycddBm'] = '';
              formModel['ycddLxdh'] = '';
            }
          },
        };
      },
      colProps: { lg: 12, md: 24 },
      required: true,
    },
    {
      label: t('订单状态'),
      field: 'ycddDdzt',
      component: 'Select',
      componentProps: {
        dictType: 'car_order_status',
        allowClear: true,
      },
      dynamicDisabled: true,
      ifShow: false,
    },
    {
      label: t('业务员'),
      field: 'ycddYwy',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
    },
    {
      label: t('联系人'),
      field: 'ycddLxr',
      //fieldLabel: 'contact.khlxrLxrmc',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    // {
    //   label: t('联系人'),
    //   field: 'ycddLxr',
    //   labelField: 'contact.khlxrLxrmc',
    //   component: 'TreeSelect',
    //   componentProps: ({ formModel, tableAction }) => {
    //     return {
    //       api: coreKhlxrTreeData,
    //       params: { parentCode: dwbm.value, bshow: isShow.value },
    //       allowClear: true,
    //       onSelect: (value, label) => {
    //         const contact = label.data;
    //         if (contact) {
    //           formModel['ycddBm'] = contact.khlxrBm;
    //           formModel['ycddLxdh'] = contact.khlxrLxdh;
    //         }
    //       },
    //       onChange: (value) => {
    //         if (!value) {
    //           formModel['ycddBm'] = '';
    //           formModel['ycddLxdh'] = '';
    //         }
    //       },
    //       onFocus: async () => {
    //         if (!dwbm.value) {
    //           isShow.value = false;
    //           showMessage('请先选择用车单位！', 'error');
    //         } else {
    //           isShow.value = true;
    //         }
    //       },
    //       onLoadData: async () => {},
    //     };
    //   },
    // },
    {
      label: t('部门'),
      field: 'ycddBm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('联系电话'),
      field: 'ycddLxdh',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('付款方式'),
      field: 'ycddFkfs',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('上车地点'),
      field: 'ycddScdd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('下车地点'),
      field: 'ycddXcdd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 12, md: 24 },
    },
    {
      label: t('用车时间'),
      field: 'datetime1',
      component: 'RangePicker',
      componentProps: ({ formModel }) => {
        return {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
          onChange: (time: dayjs | string, timeString: string) => {
            // 使用 dayjs 解析时间
            if (timeString[0] != '' && timeString[1] != '') {
              const start = dayjs(timeString[0]);
              const end = dayjs(timeString[1]);
              // 计算差异
              const duration = end.diff(start, 'second'); // 获取秒数差异
              // 转换为天数和小时数
              const days = Math.floor(duration / (24 * 60 * 60)); // 计算天数
              const hours = Math.floor((duration % (24 * 60 * 60)) / 3600); // 计算剩余的小时数
              // 设置到表单中
              formModel['ycddZcsz'] = `${days}天${hours}小时`;
            } else {
              formModel['ycddZcsz'] = '';
            }
          },
        };
      },
      colProps: { lg: 12, md: 24 },
      required: true,
    },
    {
      label: t('用车时间止'),
      field: 'ycddYcjssj',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      ifShow: false,
    },
    {
      label: t('租车时长'),
      field: 'ycddZcsz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('订单押金'),
      field: 'ycddDdyj',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('业务类型'),
      field: 'coreYwlx.id',
      fieldLabel: 'coreYwlx.ywlxLxmc',
      component: 'TreeSelect',
      componentProps: {
        api: coreYwlxTreeData,
      },
      required: true,
    },
    {
      label: t('结算方式'),
      field: 'ycddJsfs',
      component: 'Select',
      componentProps: {
        dictType: 'car_settle_tpye',
        allowClear: true,
        onSelect: (v) => {
          if (v === CarSattleType.PROJ) {
            // 专项结算
            updateSchema([{ field: 'ycddZxmc', required: true }]);
          } else {
            let obj = getFieldsValue()

            const datetime1 = ref([
              dayjs(obj.ycddYckssj, 'YYYY-MM-DD HH:mm'),
              dayjs(obj.ycddYcjssj, 'YYYY-MM-DD HH:mm'),
            ]);
            if (datetime1.value && datetime1.value[0].isValid() && datetime1.value[1].isValid()) {
              setFieldsValue({
                ...obj,
                datetime1: datetime1.value,
                ycddZxmc:'',
                'coreZxda.zxdaZxmc':'',
                ycddJsfs:v
              });
            }else{
              setFieldsValue({
                ...obj,
                ycddZxmc:'',
                'coreZxda.zxdaZxmc':'',
                ycddJsfs:v
              });
            }
            updateSchema([{ field: 'ycddZxmc', required: false }]);
          }
        },
      },
    },
    {
      label: t('专项名称'),
      field: 'ycddZxmc',
      fieldLabel: 'coreZxda.zxdaZxmc',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'zxdaSelect',
          queryParams:{
            zxdaDykh:formModel['ycddYcdw']
          },
        };
      }
    },
    {
      label: t('整单折扣'),
      field: 'ycddZdzk',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('预收金额'),
      field: 'ycddYsje',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('任务编号'),
      field: 'ycddRwbh',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('任务等级'),
      field: 'ycddRwdj',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('车辆要求'),
      field: 'ycddClyq',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('车辆行程'),
      field: 'ycddClxc',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('附件上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'carddYcdd_file',
        uploadType: 'all',
      },
      ifShow: false,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'carddYcddBtList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'carddYcddBtList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, getFieldsValue }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 6, md: 24 },
      fieldMapToTime: [
        // data为时间组件在表单内的字段，startTime，endTime为转化后的开始时间与结束时间
        ['datetime1', ['ycddYckssj', 'ycddYcjssj'], 'YYYY-MM-DD HH:mm'],
      ],
    });

  const [registerCarddYcddBtTable, carddYcddBtTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleCarddYcddBtDelete.bind(this, record),
          },
          auth: 'cardd:order:carddYcdd:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setCarddYcddBtTableData(_res: Recordable) {
    carddYcddBtTable.setColumns([
      {
        title: t('租赁方式'),
        dataIndex: 'btZlfs',
        width: 80,
        align: 'center',
        editRow: true,
        dictType: 'car_zlfs',
        editComponent: 'Select',
        // editDefaultValue: '1',
        editComponentProps: {
          dictType: 'car_zlfs',
          defaultValue: '1',
          // allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('外调类型'),
        dataIndex: 'btWdlx',
        width: 100,
        align: 'center',
        editRow: true,
        dictType: 'car_wdlx',
        editComponent: 'Select',
        // editDefaultValue: '1',
        editComponentProps: {
          dictType: 'car_wdlx',
          defaultValue: '1',
          // allowClear: true,
        },
        // editComponentProps: ({text,record}) => {
        //   return {
        //     dictType:record.editValueRefs.btZlfs == '1'?'car_wdlx':record.editValueRefs.btZlfs == '2'?'car_wdlx_dj':record.editValueRefs.btZlfs == '3'?'car_wdlx_lz':'',
        //   };
        // },
        editRule: true,
        // slot: 'wdlxSelect',
      },
      {
        title: t('是否包干'),
        dataIndex: 'btSfbgj',
        width: 80,
        align: 'center',
        editRow: true,
        dictType: 'sys_yes_no',
        editComponent: 'Select',
        editDefaultValue: '0',
        editComponentProps: {
          dictType: 'sys_yes_no',
          defaultValue: '0',
          // allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('是否点单'),
        dataIndex: 'btSfdd',
        width: 80,
        align: 'center',
        editRow: true,
        dictType: 'sys_yes_no',
        editComponent: 'Select',
        // editDefaultValue: '0',
        editComponentProps: {
          dictType: 'sys_yes_no',
          // defaultValue: '0',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('品牌型号'),
        dataIndex: 'btPpxh',
        width: 130,
        align: 'center',
        // editRow: true,
        // // editable: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'car_type',
        //   onSelect: (v) => {
        //     ppxh.value = v;
        //   },
        // },
        // dictType: 'car_type',
        // editRule: false,
        slot: 'ppxhSelect',
      },
      {
        title: t('车牌号'),
        dataIndex: 'btCph',
        width: 130,
        align: 'center',
        // editRow: true,
        // editComponentProps: {
        //   onclick: async () => {
        //     if (!ppxh.value) {
        //       showMessage('请先选择品牌型号！', 'error');
        //     } else {
        //       console.log(carSelectRef.value);
        //       queryParams.value = {
        //         cllx: ppxh.value,
        //       };
        //       await nextTick();
        //       carSelectRef.value.openSelectModal();
        //     }
        //   },
        // },
        // editRule: true,
        slot: 'cphSelect',
      },
      // {
      //   title: t('驾驶员'),
      //   dataIndex: 'btJsy',
      //   width: 130,
      //   align: 'center',
      //   editRow: true,
      //   editComponent:'Input',
      //   editComponentProps: {
      //   },
      //   editRule: false,
      //   ifShow:(text, record)=>{
      //     console.log(text, record,'text, record======999');
          
      //     return true
      //   }
      // },
      {
        title: t('驾驶员'),
        dataIndex: 'btJsy',
        width: 130,
        align: 'center',
        // editRow: true,
        // editComponent:'ListSelect',
        // editComponentProps: {
        //   selectType: 'basCusSelect',
        // },
        // editRule: false,
        slot: 'jsySelect',
      },
      {
        title: t('驾驶员编码'),
        dataIndex: 'bt_jsybm',
        width: 130,
        align: 'center',
        ifShow:false
      },
      {
        title: t('开始日期'),
        dataIndex: 'btKsrq',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: true,
      },
      {
        title: t('结束日期'),
        dataIndex: 'btJsrq',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: true,
      },
      {
        title: t('车辆行程'),
        dataIndex: 'btClxc',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('上车地点'),
        dataIndex: 'btScdd',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('上车时间'),
        dataIndex: 'btScsj',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: true,
      },
      {
        title: t('外调单位'),
        dataIndex: 'btWddw',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btWdlx != '1'?false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btWdlx  != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
                
           });
        }
      },
      {
        title: t('联系人'),
        dataIndex: 'btLxr',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btWdlx != '1'?false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btWdlx  != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
                
           });
        }
      },
      {
        title: t('联系电话'),
        dataIndex: 'btLxdh',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btWdlx != '1'?false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btWdlx  != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
                
           });
        }
      },
     
      {
        title: t('处理人'),
        dataIndex: 'btClr',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: ({text,record}) => {
          let flag = false
          if(record.editValueRefs.btZlfs != '3' && (record.editValueRefs.btWdlx == '1' || record.editValueRefs.btWdlx == '3')){
            flag = true
          }else{
            flag = false
          }

          return {
            disabled:flag
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btZlfs == '3' && !text){
                  reject('必填');
                }else if((record.editValueRefs.btZlfs == '1'|| record.editValueRefs.btZlfs == '2') &&  (record.editValueRefs.btWdlx == '2'|| record.editValueRefs.btWdlx == '4') && !text){
                  reject('必填');
                }else{
                  resolve()
                }
                
           });
        }
      },

      {
        title: t('包干价'),
        dataIndex: 'btBgj',
        width:  80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btSfbgj == '1'? false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btSfbgj == '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
           });
        }
      },
      {
        title: t('基础价'),
        dataIndex: 'btJcj',
        width:  80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btSfbgj != '1'? false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btSfbgj != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
           });
        }
      },
      {
        title: t('基础公里'),
        dataIndex: 'btJcgl',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('基础时长'),
        dataIndex: 'btJcsz',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },


      {
        title: t('超公里单价'),
        dataIndex: 'btCgldj',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btSfbgj != '1'? false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btSfbgj != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
           });
        }
      },
      {
        title: t('超时单价'),
        dataIndex: 'btCsdj',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({text,record}) => {
          return {
            disabled:record.editValueRefs.btSfbgj != '1'? false:true
          };
        },
        editRule(text, record){
           return new Promise((resolve, reject) => {
                if(record.editValueRefs.btSfbgj != '1' && !text){
                  reject('必填');
                }else{
                  resolve()
                }
           });
        }
      },
      {
        title: t('执行状态'),
        dataIndex: 'btZxzt',
        width: 130,
        align: 'center',
        dictType: 'car_order_status',
      },
      // {
      //   title: t('是否超时'),
      //   dataIndex: 'btSfcs',
      //   width: 130,
      //   align: 'center',
      //   dictType: 'sys_yes_no',
      // },

      {
        title: t('任务ID'),
        dataIndex: 'btRwid',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
    ]);
    carddYcddBtTable.setTableData(record.value.carddYcddBtList || []);
    
  }

  function handleCarddYcddBtRowClick(record: Recordable) {
    rowKey.value = record.id;
    record.onEdit?.(true, false);
  }

  function handleCarddYcddBtAdd() {
    const data = getFieldsValue();
    carddYcddBtTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      btKsrq: data.ycddYckssj ? data.ycddYckssj : '',
      btJsrq: data.ycddYcjssj ? data.ycddYcjssj : '',
      btScdd: data.ycddScdd ? data.ycddScdd : '',
      btScsj: data.ycddYckssj ? data.ycddYckssj : '',
      btZlfs:'1',
      btWdlx:'1',
      btSfbgj:'0',
      // editValueRefs:{
      //   btZlfs:'1',
      //   btWdlx:'1'
      // }
    });
  }

  function handleCarddYcddBtDelete(record: Recordable) {
    carddYcddBtTable.deleteTableDataRecord(record);
  }

  async function getCarddYcddBtList() {
    let carddYcddBtListValid = true;
    let carddYcddBtList: Recordable[] = [];
    for (const record of carddYcddBtTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        carddYcddBtListValid = false;
      }
      carddYcddBtList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of carddYcddBtTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      carddYcddBtList.push({
        ...record,
        status: '1',
      });
    }
    if (!carddYcddBtListValid) {
      throw { errorFields: [{ name: ['carddYcddBtList'] }] };
    }
    return carddYcddBtList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await carddYcddForm(data);
    record.value = (res.carddYcdd || {}) as CarddYcdd;
    record.value.__t = new Date().getTime();
    const datetime1 = ref([
      dayjs(record.value.ycddYckssj, 'YYYY-MM-DD HH:mm'),
      dayjs(record.value.ycddYcjssj, 'YYYY-MM-DD HH:mm'),
    ]);
    if (datetime1.value && datetime1.value[0].isValid() && datetime1.value[1].isValid()) {
      setFieldsValue({
        ...record.value,
        datetime1: datetime1.value,
      });
    }
    setCarddYcddBtTableData(res);
    setDrawerProps({ loading: false });
  });


    
  async function wdlxchange(value, childRecord) {
    console.log(value, childRecord,'=====');
    if(value == '1'){
      // childRecord.btWddw= ''
      // childRecord.btLxr = ''
      // childRecord. btLxdh = ''
      // childRecord.bt_jsybm = ''
      // childRecord.btJsy = ''
      carddYcddBtTable.updateTableDataRecord(childRecord.id, {
        ...childRecord,
        editValueRefs:{
          ...childRecord.editValueRefs,
          btWddw:{
            _value:''
          },
          btLxr:'',
          btLxdh:'',
        },
        bt_jsybm:'',
        btJsy:'',
      });
    }
    if(childRecord.btZlfs != '3' && (value == '1' || value == '3')){
      // childRecord.btClr = ''
      carddYcddBtTable.updateTableDataRecord(childRecord.id, {
        ...childRecord,
        editValueRefs:{
          ...childRecord.editValueRefs,
          btClr:'',
        },
        btClr:'',
      });
    }
    
  }

  async function rowChange({ column, value, record }) { 
    let { editValueRefs: { btJcj,btJcgl,btJcsz,btCgldj,btCsdj,btBgj,btWddw,btLxr,btLxdh,btClr,btZlfs,btWdlx,btPpxh,bt_jsybm,btJsy } } = record;
    
    
    // 外调类型
    if (column.dataIndex == 'btWdlx') {
      if(value == '1'){
        btWddw.value = ''
        btLxr.value = ''
        btLxdh.value = ''

        record.bt_jsybm = ''
        record.btJsy = ''
        // bt_jsybm.value = ''
        // btJsy.value = ''

        
      }
      if(btZlfs.value != '3' && (btWdlx.value == '1' || btWdlx.value == '3')){
        btClr.value = ''
      }
    }

    // 是否包干
    if (column.dataIndex == 'btSfbgj') {
      if(value == '0'){
        btBgj.value = ''
        let obj = getFieldsValue()
        if(record.btZlfs && record.btPpxh){
          let res = await coreKhjgbGetKhjgb({
            khjgbYcdw : obj.ycddYcdw,
            khjgbCllx :record.btPpxh ,
            khjgbZlfs :record.btZlfs ,
            khjgbYwlx :obj.coreYwlx.id
          })
          btJcj.value = res.data[0]?.khjgbJcj
          btJcgl.value = res.data[0]?.khjgbJcgl
          btJcsz.value = res.data[0]?.khjgbJcsz
          btCgldj.value = res.data[0]?.khjgbCgldj
          btCsdj.value = res.data[0]?.khjgbCsdj
        }

      }
      if(value == '1'){
        btJcj.value = ''
        btCgldj.value = ''
        btCsdj.value = ''
      }
    }

    
    // 租赁方式
    if (column.dataIndex == 'btZlfs') {


      if(btZlfs.value == '3'){
        record.bt_jsybm = ''
        record.btJsy = ''
        // bt_jsybm.value = ''
        // btJsy.value = ''
      }


      if(btZlfs.value == '2'){
        // btPpxh.value = ''
        record.btPpxh = ''
        record.btCph = ''
      }

      btWdlx.value = '1'


      if(btWdlx.value == '1'){
        btWddw.value = ''
        btLxr.value = ''
        btLxdh.value = ''

        record.bt_jsybm = ''
        record.btJsy = ''
        // bt_jsybm.value = ''
        // btJsy.value = ''
        
      }
      if(btZlfs.value != '3' && (btWdlx.value == '1' || btWdlx.value == '3')){
        btClr.value = ''
      }


      // record.btZlfs = value;
      let obj = getFieldsValue()
      if(btZlfs.value && record.btPpxh){
        let res = await coreKhjgbGetKhjgb({
          khjgbYcdw : obj.ycddYcdw,
          khjgbCllx : record.btPpxh ,
          khjgbZlfs :btZlfs.value ,
          khjgbYwlx :obj.coreYwlx.id
        })
        btJcj.value = res.data[0]?.khjgbJcj
        btJcgl.value = res.data[0]?.khjgbJcgl
        btJcsz.value = res.data[0]?.khjgbJcsz
        btCgldj.value = res.data[0]?.khjgbCgldj
        btCsdj.value = res.data[0]?.khjgbCsdj
      }
      
    }

    // 品牌型号
    if (column.dataIndex == 'btPpxh') {
      console.log(112233);
      // record.btPpxh = value;
      let obj = getFieldsValue()
      if(btZlfs.value && record.btPpxh){
        let res = await coreKhjgbGetKhjgb({
          khjgbYcdw : obj.ycddYcdw,
          khjgbCllx :record.btPpxh,
          khjgbZlfs :btZlfs.value ,
          khjgbYwlx :obj.coreYwlx.id
        })
        btJcj.value = res.data[0]?.khjgbJcj
        btJcgl.value = res.data[0]?.khjgbJcgl
        btJcsz.value = res.data[0]?.khjgbJcsz
        btCgldj.value = res.data[0]?.khjgbCgldj
        btCsdj.value = res.data[0]?.khjgbCsdj
      }
      
    }


  }



  async function handSelectcph(selectData, childRecord) {
   
   carddYcddBtTable.updateTableDataRecord(childRecord.id, {
     ...childRecord,
     btCph: selectData[0].cphm,
   });
 }
  async function handSelectjsy(selectData, childRecord) {
   
    carddYcddBtTable.updateTableDataRecord(childRecord.id, {
      ...childRecord,
      bt_jsybm: selectData[0].userCode,
      btJsy: selectData[0].userName,
    });
  }


  //车牌号选择
  function handleSelect(values: Recordable[]) {
    carddYcddBtTable.updateTableDataRecord(rowKey.value, {
      btCph: values[0].cphm,
      btJsy: values[0].driver ? values[0].driver.userName : '',
    });
    // 清空品牌型号
    ppxh.value = '';
  }

  async function handleSubmit(ope) {
    try {
      const data = await validate();
      if(data.ycddJsfs == CarSattleType.PROJ && !data.ycddZxmc){
        showMessage(t('请选择专项名称！'));
        return;
      }
      let jsyFlag = false
      let cphFlag = false
      let ppxhFlag = false

      let arr = carddYcddBtTable.getDataSource()
      arr.forEach(item=>{
        console.log(item,11111);
        if(item.editValueRefs.btZlfs == '1' && !item.btJsy){
          jsyFlag = true
        }

        if(item.editValueRefs.btZlfs == '2' && (item.editValueRefs.btWdlx == '1' ||item.editValueRefs.btWdlx == '2') && !item.btJsy){
          jsyFlag = true
        }


        if(item.editValueRefs.btZlfs == '1' && !item.btCph){
          cphFlag = true
        }

        if(item.editValueRefs.btZlfs == '3' && (item.editValueRefs.btWdlx == '1' ||item.editValueRefs.btWdlx == '3') && !item.btCph){
          cphFlag = true
        }

        if(item.editValueRefs.btZlfs == '1' && !item.btPpxh){
          ppxhFlag = true
        }

        if(item.editValueRefs.btZlfs == '3' && (item.editValueRefs.btWdlx == '1' ||item.editValueRefs.btWdlx == '3') && !item.btPpxh){
          ppxhFlag = true
        }
      })
      if(ppxhFlag){
        showMessage(t('品牌型号必填！'));
        return;
      }

      if(cphFlag){
        showMessage(t('车牌号必填！'));
        return;
      }

      if(jsyFlag){
        showMessage(t('驾驶员必填！'));
        return;
      }

      
     


      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.carddYcddBtList = await getCarddYcddBtList();



      if (ope) {
        data.ope = ope;
      }
      // console.log('submit', params, data, record);
      const res = await carddYcddSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
